<template>
  <div class="text-h6 text-weight-medium text-primary ellipsis cursor-hover cursor-pointer"
       @click.stop="toggleBaseVisible">
    {{ $t('MapCore.PointAttrsTip1') }}
  </div>
  <q-slide-transition>
    <div v-show="baseVisible">
      <div v-if="!readonly" class="warning-tips text-weight-medium text-body2 q-mb-md">
        <q-icon class="map-warning-tips-icon" name="mdi-information-outline" size="1.25rem"></q-icon>
        {{ $t('MapCore.SaveTip1', [$t('MapCore.SaveMap')]) }}
      </div>
      <qx-form v-model="baseForm" :option="baseOption" nonTop @submit="submitBaseAttrs">
        <template v-slot:absoluteCoord="{ attrs = {} }">
          <div class="row justify-between no-wrap">
            <q-number v-model="baseForm.x" :readonly="readonly" class="col" decimals="3" v-bind="attrs"
                      v-bind:placeholder="'x'" v-bind:rules="getRules('X')" @blur="numBlur"></q-number>
            <div class="row items-end q-px-xs">,</div>
            <q-number v-model="baseForm.y" :readonly="readonly" class="col" decimals="3" v-bind="attrs"
                      v-bind:placeholder="'y'" v-bind:rules="getRules('Y')" @blur="numBlur"></q-number>
          </div>
        </template>
        <template v-slot:menuRight="{ scope = {} }">
          <q-btn icon="cancel_schedule_send" outline text-color="primary" v-bind="scope" @click="emits('handleClose')">
            {{ $t('Close') }}
          </q-btn>
        </template>
      </qx-form>
    </div>
  </q-slide-transition>
  <template v-if="!isBatch">
    <q-separator class="q-mt-sm"></q-separator>
    <div class="text-h6 text-weight-medium text-primary ellipsis q-pt-sm cursor-hover cursor-pointer"
         @click.stop="toggleServiceVisible">
      {{ $t('MapCore.PointAttrsTip2') }}
    </div>
    <q-slide-transition appear>
      <div v-show="serviceVisible">
        <div v-if="!readonly" class="warning-tips text-weight-medium text-body2 q-mb-md">
          <q-icon class="map-warning-tips-icon" name="mdi-information-outline" size="1.25rem"></q-icon>
          {{ $t('MapCore.SaveTip2', [$t('Submit')]) }}
        </div>
        <qx-form v-model="serviceForm" :option="serviceOption" nonTop @submit="submitServiceAttrs">
          <template v-slot:coord>
            <div class="row text-grey-7 items-center">
              {{ rowInfo?.x }}, {{ rowInfo?.y }}
            </div>
          </template>
          <template v-slot:menuRight="{ scope = {} }">
            <q-btn icon="cancel_schedule_send" outline text-color="primary" v-bind="scope"
                   @click="emits('handleClose')">
              {{ $t('Close') }}
            </q-btn>
          </template>
        </qx-form>
      </div>
    </q-slide-transition>
  </template>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import { postAPI } from 'src/api'
import { getRemoteData } from 'src/enum/ajaxRemoteData.js'
import { createSuccessTips, deepClone, isEmpty } from 'src/utils/utils'
import { directional } from 'src/views/CarrierCore/enum.js'
import {
  formatRackDirections, IsAvoidable, IsRotatable, NavigationTypes, Quadrants, stationDirections
} from 'src/views/MapCore/enum.js'
import { packagePoints } from 'src/views/MapCore/MapGlobal/utils/PackagePoints.js'
import { computed, inject, nextTick, ref, watch } from 'vue'

const props = defineProps({
  rowInfo: Object, loading: Boolean, isBatch: Boolean, readonly: Boolean, modalVisible: Boolean
})
const updateShapeAttrs = inject('updateShapeAttrs', void 0)
const updateShapeCoord = inject('updateShapeCoord', void 0)
const batchUpdateShapeAttrs = inject('batchUpdateShapeAttrs', void 0)
const emits = defineEmits(['handleClose', 'update:loading'])

const racks = ref([])
const baseForm = ref({})
const AGVModels = ref([])
const serviceForm = ref({})
const baseVisible = ref(true)
const serviceVisible = ref(true)

const filterIsRotatable = computed(() => IsRotatable.value.filter(el => el.value !== '2'))
const filterDirectional = computed(() => directional.value.filter(el => el.value !== '-1'))
const baseOption = computed(() => {
  return {
    span: 24, labelWidth: 90, resetBtn: false, labelPosition: 'left',
    readonly: props.readonly, menuBtn: !props.readonly, submitText: i18n.t('Staging'),
    column: [{
      label: `${i18n.t('MapCore.StationType')}`, field: 'pointType', type: 'select', options: packagePoints.value,
      props: { label: 'positionPackageName', value: 'positionPackageCode' }, required: !props.isBatch
    }, {
      label: `${i18n.t('MapCore.StationCoord')}(m)`, field: 'absoluteCoord', formslot: true, required: true,
      display: !props.isBatch
    }, {
      label: `${i18n.t('MapCore.StationName')}`, field: 'pointName', display: !props.isBatch
    }]
  }
})
const serviceOption = computed(() => {
  return {
    span: 24, labelWidth: 90, resetBtn: false, labelPosition: 'left', readonly: props.readonly,
    menuBtn: !props.readonly,
    column: [{
      label: `${i18n.t('StationAttrs.RoadBack')}`, field: 'roadProperty', type: 'switch', falseValue: '0',
      trueValue: '1', value: '1', class: 'custom-switch'
    }, {
      label: `${i18n.t('CarrierCore.RackDirection')}`, field: 'allDir', type: 'radio',
      options: formatRackDirections.value, value: '9'
    }, {
      label: `${i18n.t('StationAttrs.SiteDirection')}`, field: 'eleDir', type: 'radio',
      options: stationDirections.value, value: '999'
    }, {
      label: `${i18n.t('StationAttrs.BordEntryDirection')}`, field: 'agvInDir'
    }, {
      label: `${i18n.t('StationAttrs.RotateAvoidance')}`, field: 'rotarySwitch', type: 'switch', falseValue: '0',
      trueValue: '1', value: '0', class: 'custom-switch'
    }, {
      label: `${i18n.t('StationAttrs.RotateAvoidanceRadius')}(mm)`, field: 'rotRad', type: 'number', value: '0',
      decimals: 0, min: -1000, max: 3000, display: serviceForm.value.rotarySwitch === '1'
    }, {
      label: `${i18n.t('StationAttrs.AllowedVehicleType')}`, field: 'roBotType', type: 'select', multiple: true,
      value: '-1', options: AGVModels.value, props: { label: 'deviceName', value: 'deviceCode' }
    }, {
      label: `${i18n.t('StationAttrs.RackUnderRotation')}`, field: 'rotUnderPod', type: 'select',
      options: IsRotatable.value, value: '0'
    }, {
      label: `${i18n.t('StationAttrs.LiftingPlate')}`, field: 'rotMech', type: 'radio',
      options: filterIsRotatable.value, value: '0'
    }, {
      label: `${i18n.t('StationAttrs.IsAvoidable')}`, field: 'evit', type: 'select',
      options: IsAvoidable.value, value: '0'
    }, {
      label: `${i18n.t('StationAttrs.RotatingModel')}`, field: 'rotByRoBotType', type: 'select', multiple: true,
      value: '-1', options: AGVModels.value, props: { label: 'deviceName', value: 'deviceCode' }
    }, {
      label: `${i18n.t('StationAttrs.RotatingRack')}`, field: 'rotForPodType', type: 'select', multiple: true,
      value: '-1', options: racks.value, props: { label: 'originalLabel', value: 'label' }
    }, {
      label: `${i18n.t('StationAttrs.PalletRecognition')}`, field: 'palletRecogniTion', type: 'switch',
      falseValue: '0', trueValue: '1', value: '0', class: 'custom-switch'
    }, {
      label: `${i18n.t('StationAttrs.RotatingObstacleZone')}`, field: 'rotBarrierArea', type: 'select',
      multiple: true, options: Quadrants.value
    }, {
      label: `${i18n.t('MapCore.RefreshMap')}`, field: 'isUpdateMap', type: 'switch', falseValue: '0',
      trueValue: '1', value: '1', class: 'custom-switch'
    }, {
      label: `${i18n.t('StationAttrs.CTUForwardDocking')}`, field: 'ctuStance', type: 'switch', falseValue: '0',
      trueValue: '1', value: '1', class: 'custom-switch'
    }, {
      label: `${i18n.t('StationAttrs.IsPause')}`, field: 'tranZoneType', type: 'switch',
      falseValue: '0', trueValue: '1', value: '0', class: 'custom-switch'
    }, {
      label: `${i18n.t('StationAttrs.PausePriority')}`, field: 'priority', type: 'number', decimals: 0,
      min: 1, max: 127, display: serviceForm.value.tranZoneType === '1'
    }, {
      label: `${i18n.t('StationAttrs.LinkedForkliftWaitPoint')}`, field: 'forkWaitPos'
    }, {
      label: `${i18n.t('StationAttrs.LeaveCurrentPointDistance')}`, field: 'outFromBinDis', type: 'number',
      value: '0', decimals: 0, min: 0, max: 10000, display: ['22'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('AGVCore.NavigationType')}`, field: 'mapCrossType', type: "radio",
      options: NavigationTypes.value, value: '0', display: ['26'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.HandoverCodeType')}`, field: 'qrCode',
      display: ['26'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.HandoverXCoord')}(m)`, field: 'xposNew', type: 'number', value: '0', decimals: 3,
      min: 0, max: 1000, display: ['26'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.HandoverYCoord')}(m)`, field: 'yposNew', type: 'number', value: '0', decimals: 3,
      min: 0, max: 1000, display: ['26'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.HandoverCoordOffset')}`, field: 'ncoor', type: 'radio', value: '0',
      options: filterDirectional.value, display: ['26'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.XCodeSpacing')}`, field: 'stepXpos', type: 'number', decimals: 0, min: 0,
      max: 9999, display: ['33'].includes(serviceForm.value.pointType)
    }, {
      label: `${i18n.t('StationAttrs.YCodeSpacing')}`, field: 'stepYpos', type: 'number', decimals: 0, min: 0,
      max: 9999, display: ['33'].includes(serviceForm.value.pointType)
    }]
  }
})

const getRules = coord => {
  return [val => !isEmpty(val) || `${i18n.t('PleaseInput')}${i18n.t('MapCore.SpecifyCoord', { coord })}`]
}
const numBlur = () => updateShapeCoord && updateShapeCoord(baseForm.value)
const toggleBaseVisible = () => (baseVisible.value = !baseVisible.value)
const toggleServiceVisible = () => {
  serviceVisible.value = !serviceVisible.value
  if (!props.isBatch && !serviceForm.value.pointType && serviceVisible.value) getServiceForm()
}
const getServiceForm = () => {
  if (!AGVModels.value.length) {
    getRemoteData('agv_model', '/yfagv/api/agvTypeDevice/list').then(data => {
      AGVModels.value = [{ deviceName: i18n.t('All'), deviceCode: '-1' }, ...data]
    })
  }
  if (!racks.value.length) {
    getRemoteData('agv_rack', '/yfagv/api/agvMasDataShelfBase/shelfTypeList').then(data => {
      racks.value = [{ originalLabel: i18n.t('All'), label: '-1' }, ...data]
    })
  }
  const params = {
    mapGroundCode: baseForm.value.mapGroundCode, positionPackageCode: baseForm.value.pointType,
    positionX: baseForm.value.x, positionY: baseForm.value.y
  }
  emits('update:loading', true)
  postAPI('/yfagv/api/mapPointBusinessInfo/findMapPointBusinessInfoBy', params, data => {
    serviceForm.value = data || {}
    emits('update:loading', false)
  }, () => emits('update:loading', false))
}
const getBaseForm = () => {
  baseForm.value = deepClone(props.rowInfo || {})
  if (props.isBatch) return
  if (serviceVisible.value) {
    if (!serviceForm.value.pointType) nextTick(() => (serviceVisible.value = false))
    else getServiceForm()
  } else serviceForm.value = {}
}
watch([() => props.rowInfo?.x, () => props.rowInfo?.y], () => getBaseForm(), { immediate: true })

const submitBaseAttrs = (form, done) => {
  const updateShape = props.isBatch ? batchUpdateShapeAttrs : updateShapeAttrs
  if (!updateShape) return
  emits('update:loading', true)
  updateShape && updateShape(form, done, emits('update:loading', false))
}
const submitServiceAttrs = (form, done) => {
  emits('update:loading', true)
  const { mapGroundCode, x, y } = baseForm.value
  form.positionX = x
  form.positionY = y
  form.mapGroundCode = mapGroundCode
  if (form.roBotType.includes('-1')) form.roBotType = '-1'
  if (form.rotForPodType.includes('-1')) form.rotForPodType = '-1'
  if (form.rotByRoBotType.includes('-1')) form.rotByRoBotType = '-1'
  postAPI('/yfagv/api/mapPointBusinessInfo/updateOrSaveMapPointBusinessInfo', form, () => {
    createSuccessTips({ title: `${i18n.t('LogCore.OperationTip')}` })
    done()
    emits('update:loading', false)
  }, () => {
    done()
    emits('update:loading', false)
  })
}
</script>